package com.ruoyi.eqmonitor.dispose.resolve;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONArray;
import com.ruoyi.eqmonitor.dispose.mapper.MonitorDataMapper;
import com.ruoyi.eqmonitor.dtos.OptDeviceDto;
import com.ruoyi.eqmonitor.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监测数据处理
 *
 * @author dh
 */
@Slf4j
@Component
public class MonitorResolve implements MqttMessageResolve {

    private static final Logger dataLogger = LoggerFactory.getLogger("monitor_data");

    @Resource
    private MonitorDataMapper monitorDataMapper;

    @Override
    public boolean support(int msgType) {
        return Constant.MqttMsgType.MONITOR_DATA.getCode() == msgType;
    }

    /**
     * 解析处理
     * @param snCode 设备编码
     * @param messageArray 消息
     */
    @Override
    public boolean resolve(String snCode, OptDeviceDto optDevice, JSONArray messageArray) {
        long start = System.currentTimeMillis();
        String version = UUID.fastUUID().toString();
        // 打印日志
        log.debug("snCode:{}, deviceCode: {}, 消息流水: {}, 接收到监测实时数据:{}", snCode, optDevice.getDeviceCode(), version, messageArray);
        dataLogger.info("snCode:{}, deviceCode: {}, 消息流水: {}, 接收到监测实时数据:{}", snCode, optDevice.getDeviceCode(), version, messageArray);
        try {
            monitorDataMapper.write(snCode, optDevice, messageArray, version);
            log.info("snCode:{}, deviceCode: {}, 消息流水: {}, 全部存储成功, 耗时: {}", snCode, optDevice.getDeviceCode(), version, (System.currentTimeMillis() - start));
        } catch (Exception e) {
            log.error("snCode:{}, deviceCode: {}, 消息流水: {}, 存储失败。 \n {}", snCode, optDevice.getDeviceCode(), version, messageArray, e);
        }
        return true;
    }
}
